package com.example.fwx;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.baidu.aip.imageclassify.AipImageClassify;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ImageRecognitionFragment extends Fragment {

    // 百度AI配置 - 请替换为您的实际配置
    private static final String APP_ID = "119161161";
    private static final String API_KEY = "CmJK0yZYd28twg2wgKl2yKAx";
    private static final String SECRET_KEY = "q2VPEbjvDo9lMdTA0cq1q7e0zisU5GtW";

    private TextView textViewResult;
    private ImageView imageViewSelected;
    private Button buttonGallery;
    private AipImageClassify client;
    private ExecutorService executorService;

    // 创建图库选择结果接收器
    private final ActivityResultLauncher<Intent> galleryLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (result.getResultCode() == requireActivity().RESULT_OK && result.getData() != null) {
                    Uri selectedImageUri = result.getData().getData();
                    if (selectedImageUri != null) {
                        try {
                            Bitmap bitmap = MediaStore.Images.Media.getBitmap(
                                    requireActivity().getContentResolver(), selectedImageUri);
                            imageViewSelected.setImageBitmap(bitmap);
                            recognizeImage(bitmap);
                        } catch (IOException e) {
                            e.printStackTrace();
                            Toast.makeText(requireContext(), "加载图片失败: " + e.getMessage(),
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            });

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 初始化百度AI客户端
        try {
            client = new AipImageClassify(APP_ID, API_KEY, SECRET_KEY);
            // 可选：设置网络连接参数
            client.setConnectionTimeoutInMillis(2000);
            client.setSocketTimeoutInMillis(60000);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(requireContext(), "初始化AI服务失败", Toast.LENGTH_SHORT).show();
        }
        executorService = Executors.newSingleThreadExecutor();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_image_recognition, container, false);

        // 初始化视图组件
        textViewResult = view.findViewById(R.id.text_result);
        buttonGallery = view.findViewById(R.id.button_gallery);
        imageViewSelected = view.findViewById(R.id.image_selected);

        // 设置初始状态
        textViewResult.setText("请选择图片进行识别");

        // 设置按钮点击监听器
        buttonGallery.setOnClickListener(v -> {
            openGallery();
        });

        return view;
    }

    /**
     * 打开图库选择图片
     */
    private void openGallery() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*");
        galleryLauncher.launch(intent);
    }

    /**
     * 图像识别方法
     */
    private void recognizeImage(Bitmap bitmap) {
        // 检查网络连接
        if (!isNetworkConnected()) {
            Toast.makeText(requireContext(), "请检查网络连接后重试", Toast.LENGTH_SHORT).show();
            return;
        }

        // 检查AI客户端是否初始化成功
        if (client == null) {
            Toast.makeText(requireContext(), "AI服务未初始化，请重试", Toast.LENGTH_SHORT).show();
            return;
        }

        // 显示加载状态
        textViewResult.setText("正在识别图像，请稍候...");
        buttonGallery.setEnabled(false);

        // 在后台线程执行API调用
        executorService.execute(() -> {
            try {
                // 将Bitmap转换为byte数组
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 80, baos);
                byte[] imageBytes = baos.toByteArray();

                // 调用百度AI通用物体识别
                HashMap<String, String> options = new HashMap<>();
                options.put("baike_num", "5"); // 返回百科信息的结果数
                options.put("with_face", "1"); // 是否检测人脸

                JSONObject res = client.advancedGeneral(imageBytes, options);

                // 在主线程更新UI
                if (getActivity() != null && !getActivity().isFinishing()) {
                    requireActivity().runOnUiThread(() -> {
                        buttonGallery.setEnabled(true);
                        displayRecognitionResult(res);
                    });
                }

            } catch (Exception e) {
                e.printStackTrace();
                if (getActivity() != null && !getActivity().isFinishing()) {
                    requireActivity().runOnUiThread(() -> {
                        buttonGallery.setEnabled(true);
                        Toast.makeText(requireContext(), "识别失败: " + e.getMessage(),
                                Toast.LENGTH_SHORT).show();
                        textViewResult.setText("识别失败，请重试\n\n错误信息：" + e.getMessage());
                    });
                }
            }
        });
    }

    /**
     * 显示识别结果
     */
    private void displayRecognitionResult(JSONObject result) {
        try {
            StringBuilder resultText = new StringBuilder();
            resultText.append("🔍 图像识别结果\n");
            resultText.append("=" .repeat(30)).append("\n\n");

            // 检查是否有错误
            if (result.has("error_code")) {
                int errorCode = result.getInt("error_code");
                String errorMsg = result.optString("error_msg", "未知错误");
                resultText.append("❌ 识别失败\n");
                resultText.append("错误代码: ").append(errorCode).append("\n");
                resultText.append("错误信息: ").append(errorMsg);
            } else if (result.has("result")) {
                JSONArray resultArray = result.getJSONArray("result");

                if (resultArray.length() > 0) {
                    resultText.append("✅ 识别成功！\n\n");
                    resultText.append("识别到的物体：\n");

                    for (int i = 0; i < Math.min(resultArray.length(), 5); i++) {
                        JSONObject item = resultArray.getJSONObject(i);
                        String keyword = item.getString("keyword");
                        double score = item.getDouble("score");

                        resultText.append(String.format("%d. %s\n", i + 1, keyword));
                        resultText.append(String.format("   置信度: %.1f%%\n", score * 100));

                        // 如果有百科信息
                        if (item.has("baike_info")) {
                            JSONObject baikeInfo = item.getJSONObject("baike_info");
                            if (baikeInfo.has("description")) {
                                String description = baikeInfo.getString("description");
                                if (!description.isEmpty()) {
                                    // 限制描述长度
                                    if (description.length() > 100) {
                                        description = description.substring(0, 100) + "...";
                                    }
                                    resultText.append("   简介: ").append(description).append("\n");
                                }
                            }
                        }
                        resultText.append("\n");
                    }
                } else {
                    resultText.append("❓ 未识别到相关内容\n");
                    resultText.append("建议：\n");
                    resultText.append("• 确保图片清晰\n");
                    resultText.append("• 物体占据画面主要部分\n");
                    resultText.append("• 光线充足");
                }

                // 显示识别结果总数
                resultText.append(String.format("\n📊 共识别到 %d 个对象", resultArray.length()));
            } else {
                resultText.append("⚠️ 识别结果格式异常");
            }

            textViewResult.setText(resultText.toString());

        } catch (JSONException e) {
            e.printStackTrace();
            textViewResult.setText("❌ 解析识别结果失败\n\n错误信息：" + e.getMessage());
        }
    }

    /**
     * 检查网络连接
     */
    private boolean isNetworkConnected() {
        ConnectivityManager cm = (ConnectivityManager) requireContext()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm != null) {
            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
        }
        return false;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 清理资源
        if (executorService != null && !executorService.isShutdown()) {
            executorService.shutdown();
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        // 确保没有内存泄漏
        client = null;
    }
}